package com.chao.yyks.modular.config.service.impl;


import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.chao.yyks.modular.config.mapper.ResourceMapper;
import com.chao.yyks.modular.config.service.FdfsService;
import com.chao.common.util.Base64DecodedMultipartFile;
import com.chao.common.util.DateUtile;
import com.chao.common.util.StrUtile;
import com.chao.common.util.exception.SysException;
import com.chao.common.util.file.FileUpload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class FdfsServiceImpl implements FdfsService {

    @Value("${config.gofdfs.filePrefix}")
    private String filePrefix;

    @Value("${config.gofdfs.upload}")
    private String upload;

    @Autowired
    private ResourceMapper resourceMapper;

    /**
     * 附件类型
     */
    private static List<String> FILE_TYPE = Arrays.asList("txt", "doc", "xls", "docx", "xlsx", "pptx", "ppt", "jpg", "png", "jpeg", "bmp", "gif", "pdf", "tiff", "swf", "mp4", "sys");

    @Override
    public FileUpload uploadFile(MultipartFile file) {
        String result = "";
        String fileType = "";
        try {
            String fileName = file.getOriginalFilename();
            if (null != fileName && fileName.contains(".")) {
                String[] s = fileName.split("\\.");
                fileType = s[s.length - 1];
            } else {
                fileType = "sys";
            }
            checkType(fileType);
            InputStreamResource isr = new InputStreamResource(file.getInputStream(), StrUtile.getUUID() + "." + fileType);
            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            params.put("path", "default/" + DateUtile.toymd());
            params.put("output", "json");
            String str = HttpUtil.post(upload, params);
            log.info("文件结果=" + str);
            JSONObject json = JSONObject.parseObject(str);
            if (json.containsKey("path")) {
                result = json.getString("path");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setFilePrefix(filePrefix);
        fileUpload.setFileUrl(result);
        fileUpload.setFileType(fileType);
        return fileUpload;
    }

    /**
     * 文件上传
     */
    @Override
    public FileUpload uploadByteFile(byte[] bytes, String fileName) {
        String result = "";
        try {
            String fileType;
            if (fileName.contains(".")) {
                String[] s = fileName.split("\\.");
                fileType = s[s.length - 1];
            } else {
                fileType = "sys";
            }
            checkType(fileType);
            InputStreamResource isr = new InputStreamResource(new ByteArrayInputStream(bytes), StrUtile.getUUID() + "." + fileType);
            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            params.put("path", "default/" + DateUtile.toymd());
            params.put("output", "json");
            String str = HttpUtil.post(upload, params);
            JSONObject json = JSONObject.parseObject(str);
            if (json.containsKey("path")) {
                result = json.getString("path");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(fileName);
        fileUpload.setFilePrefix(filePrefix);
        fileUpload.setFileUrl(result);
        return fileUpload;
    }

    @Override
    public FileUpload uploadThisFile(File file) {
        String result = "";
        String fileName = file.getName();
        try {
            String fileType;
            if (fileName.contains(".")) {
                String[] s = fileName.split("\\.");
                fileType = s[s.length - 1];
            } else {
                fileType = "sys";
            }
            checkType(fileType);
            fileName = StrUtile.getUUID() + "." + fileType;
            InputStreamResource isr = new InputStreamResource(Files.newInputStream(file.toPath()), fileName);
            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            params.put("path", "default/" + DateUtile.toymd());
            params.put("output", "json");
            String str = HttpUtil.post(upload, params);
            JSONObject json = JSONObject.parseObject(str);
            if (json.containsKey("path")) {
                result = json.getString("path");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(fileName);
        fileUpload.setFilePrefix(filePrefix);
        fileUpload.setFileUrl(result);
        return fileUpload;
    }

    @Override
    public FileUpload uploadFileBase64(String base64, String fileName) {
        String result = "";
        try {

            // 文件类型校验
            if (fileName.contains(".")) {
                String[] s = fileName.split("\\.");
                String fileType1 = s[s.length - 1];
                checkType(fileType1);
            }

            String fileType = "jpg";
            //转化为输入流
            MultipartFile multipartFile = Base64DecodedMultipartFile.base64ToMultipart(base64);
            InputStreamResource isr = new InputStreamResource(multipartFile.getInputStream(), StrUtile.getUUID() + "." + fileType);
            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            params.put("path", "default/" + DateUtile.toymd());
            params.put("output", "json");
            String str = HttpUtil.post(upload, params);
            JSONObject json = JSONObject.parseObject(str);
            if (json.containsKey("path")) {
                result = json.getString("path");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(fileName);
        fileUpload.setFilePrefix(filePrefix);
        fileUpload.setFileUrl(result);
        return fileUpload;
    }

    /**
     * 附件下载
     *
     * @param fileId
     */
    @Override
    public void downLoadFile(HttpServletResponse response, String fileId) throws IOException {
        FileUpload resource = resourceMapper.selectResourceByFileId(fileId);
        if (null == resource) {
            return;
        }
        String httpUrl = resource.getFilePrefix() + resource.getFileUrl();
        ServletOutputStream out = null;
        try {
            // 与服务器建立连接
            URL url = new URL(httpUrl);
            URLConnection conn = url.openConnection();
            InputStream inputStream = conn.getInputStream();
            String fileName = "";
            try {
                //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
                response.setContentType("multipart/form-data");
                fileName = URLEncoder.encode(resource.getFileName(), "UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SysException("附件下载失败!");
        } finally {
            out.close();
        }

    }

    /**
     * 文件类型校验
     *
     * @param fileType **.**
     */
    public void checkType(String fileType) {
//        if (!FILE_TYPE.contains(fileType.toLowerCase())) {
//            throw new SysException("文件类型错误，供参考文件类型：txt,doc,xls,docx,xlsx,pptx,ppt,jpg,png,jpeg,bmp,gif,pdf,tiff,swf,mp4!");
//        }
    }

//    public static void main(String[] args) {
//        File file = new File("C:\\Users\\Administrator\\Desktop\\dbac13dce79d51b1a8472462d46cf6f2.mp4");
//        String result = "";
//        String fileName = file.getName();
//        try {
//            String fileType;
//            if (fileName.contains(".")) {
//                String[] s = fileName.split("\\.");
//                fileType = s[s.length - 1];
//            } else {
//                fileType = "sys";
//            }
//            fileName = StrUtile.getUUID() + "." + fileType;
//            InputStreamResource isr = new InputStreamResource(Files.newInputStream(file.toPath()), fileName);
//            Map<String, Object> params = new HashMap<>();
//            params.put("file", isr);
//            params.put("path", "default/" + DateUtile.toymd());
//            params.put("output", "json");
//            String str = HttpUtil.post("http://47.98.247.29:8888/group1/upload", params);
//            System.out.println(str);
//            JSONObject json = JSONObject.parseObject(str);
//            if (json.containsKey("path")) {
//                result = json.getString("path");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

}
